package com.luck.emp.ass.logic;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.jdbc.core.RowMapper;

import com.luck.emp.ass.AssVo;
import com.luck.emp.ass.qry.AssQry;
import com.luck.emp.common.SpOrderNoTwo;
import com.luck.emp.common.SpWhOrderD;
import com.luck.emp.common.SpWhOrderM;
import com.luck.emp.entity.EmpTProdAss;
import com.luck.emp.entity.EmpTWhAssD;
import com.luck.emp.entity.EmpTWhAssM;
import com.luck.emp.product.logic.IProductLogic;
import com.luck.pf.common.entity.UserBean;
import com.luck.pf.framework.dao.BaseJdbcDao;
import com.luck.pf.framework.logic.BaseLogic;
import com.luck.pf.util.CriteriaUtil;
import com.luck.pf.util.DateUtil;
import com.luck.pf.util.Page;

/**
 * 说明
 * Copyright: Copyright (c) 2011
 * 深圳**科技
 * @author 
 * 
 */
public class AssLogic extends BaseLogic implements IAssLogic{
	private BaseJdbcDao jdbcDao;
	private IProductLogic productLogic;
	
	public BaseJdbcDao getJdbcDao() {
		return jdbcDao;
	}

	public void setJdbcDao(BaseJdbcDao jdbcDao) {
		this.jdbcDao = jdbcDao;
	}

	public IProductLogic getProductLogic() {
		return productLogic;
	}

	public void setProductLogic(IProductLogic productLogic) {
		this.productLogic = productLogic;
	}

	/**
	 * 查找分页信息
	 */
	public Page findAssPage(AssQry qry){
		Criteria criteria = baseDao.createCriteria(EmpTWhAssM.class);		
		    CriteriaUtil.addEq(criteria, "billType", qry.getBillType());
		    CriteriaUtil.addEq(criteria, "assCode", qry.getAssCode());
			criteria.add(Restrictions.between("createDate",
					DateUtil.getStartDateDay(qry.getStartDate()),
					DateUtil.getEndDateDay(qry.getEndDate())));
		Order order=Order.desc("createDate");
		criteria.addOrder(order);
		criteria.createAlias("dept", "d");
		filterData(criteria, qry.getUserInfo(), "d", null);
		return baseDao.pagedQuery(criteria,qry.getPageNo(),qry.getPageSize());
	}

	@Override
	public String saveAss(UserBean userBean, EmpTWhAssM entity) throws Exception {
		//生成组装拆卸单
		String assCode = null;
		String billType = entity.getBillType();
		synchronized(this){
			SpOrderNoTwo sp = new SpOrderNoTwo(this.jdbcDao.getJdbcTemplate());
			if(billType.equals("16"))
				assCode = sp.execute(userBean.getDept().getDeptCode(), "ZZ");
			else if(billType.equals("17"))
				assCode = sp.execute(userBean.getDept().getDeptCode(), "CX");
			entity.setAssCode(assCode);
			entity.setCreateDate(DateUtil.getDate());
			entity.setCreateUser(userBean.getUser());
			entity.setDeptId(userBean.getDeptId());
			super.save(entity);				
			if(billType.equals("16")){//组装单，先将散件出库，然后将整件入库,io_type 47:组装单出库
				SpWhOrderM spwo = new SpWhOrderM(this.jdbcDao.getJdbcTemplate());
				//新建出库订单主表
				String orderCode = spwo.execute(billType, 20L, assCode, entity.getWhCode(), null,
						null, null, null, entity.getNote(), userBean.getUserId(), "47", null, null, null);
				//新建出库订单详细表
				List<EmpTProdAss> assvo = productLogic.findProdAssRel(entity.getProductCode());
				SpWhOrderD spd = new SpWhOrderD(this.jdbcDao.getJdbcTemplate());
				for(EmpTProdAss vo:assvo){
					spd.execute(orderCode, vo.getId().getProductCodeSub(), vo.getQty()*entity.getQty(), 0, 0, userBean.getUserId(), null);
					EmpTWhAssD assd = new EmpTWhAssD();
					assd.setAssCode(assCode);
					assd.setProductCode(vo.getId().getProductCodeSub());
					assd.setQty(vo.getQty()*entity.getQty());
					super.baseDao.save(assd);
				}
				
				//新建入库订单主表，将组装商品入库,io_type:16,组装单入库
				String inorderCode = spwo.execute(billType, 20L, assCode, entity.getWhCode(), null,
						null, null, null, entity.getNote(), userBean.getUserId(), "16", null, null, null);
				spd.execute(inorderCode, entity.getProductCode(), entity.getQty(), 0, 0, userBean.getUserId(), null);
				
			}
			if(billType.equals("17")){//拆卸单,先将整件出库，然后将散件入库
				SpWhOrderM spwo = new SpWhOrderM(this.jdbcDao.getJdbcTemplate());
				//新建出库订单主表
				String orderCode = spwo.execute(billType, 20L, assCode, entity.getWhCode(), null,
						null, null, null, entity.getNote(), userBean.getUserId(), "47", null, null, null);
				//新建出库订单详细表
				SpWhOrderD spd = new SpWhOrderD(this.jdbcDao.getJdbcTemplate());
				spd.execute(orderCode, entity.getProductCode(), entity.getQty(), 0, 0, userBean.getUserId(), null);

				//新建入库订单主表，将组装商品入库,io_type:16,组装单入库
				String inorderCode = spwo.execute(billType, 20L, assCode, entity.getWhCode(), null,
						null, null, null, entity.getNote(), userBean.getUserId(), "16", null, null, null);
				List<EmpTProdAss> assvo = productLogic.findProdAssRel(entity.getProductCode());
				for(EmpTProdAss vo:assvo){
					spd.execute(inorderCode, vo.getId().getProductCodeSub(), vo.getQty()*entity.getQty(), 0, 0, userBean.getUserId(), null);
					EmpTWhAssD assd = new EmpTWhAssD();
					assd.setAssCode(assCode);
					assd.setProductCode(vo.getId().getProductCodeSub());
					assd.setQty(vo.getQty()*entity.getQty());
					super.baseDao.save(assd);
				}
			}

		}
		return null;
	}

	public List<AssVo> findAssVos(String productCode, String whCode) {
		StringBuffer sql = new StringBuffer();
		Map params = new HashMap();
		
		sql.append("select b.V_PRODUCT_CODE,                                               ");
		sql.append("       nvl(a.leave_qty, 0) leave_qty,                                     ");
		sql.append("       b.V_NAME V_PRODUCT_NAME,                                                     ");
		sql.append("       C. PARAM_NAME V_MEAS_UNIT,                                                        ");
		sql.append("       b.n_qty                                                            ");
		sql.append("  from (select wb.V_PRODUCT_CODE, sum(wb.N_QTY) leave_qty              ");
		sql.append("          from EMP_T_WH_BALANCE wb                                           ");
		sql.append("         where wb.v_wh_code = :whCode                                  ");
		sql.append("           and wb.V_PRODUCT_CODE in                                    ");
		sql.append("               (select x.V_PRODUCT_CODE_SUB                            ");
		sql.append("                  from EMP_T_PROD_ASS x                               ");
		sql.append("                 where x.V_PRODUCT_CODE = :productCode)              ");
		sql.append("         group by wb.V_PRODUCT_CODE) a,                                ");
		sql.append("       (select sb.V_PRODUCT_CODE, sb.V_NAME, sb.V_MEAS_UNIT, b.n_qty ");
		sql.append("          from EMP_T_PROD_ASS b, EMP_T_PROD_BASE sb               ");
		sql.append("         where b.V_PRODUCT_CODE_SUB = sb.V_PRODUCT_CODE             ");
		sql.append("           and b.V_PRODUCT_CODE = :productCode) b,                    ");
		sql.append(" (SELECT * FROM SYS_PARAMS T WHERE T.PARAM_CODE = 'p_meas_unit') C");
		sql.append(" where b.V_PRODUCT_CODE = a.V_PRODUCT_CODE(+)                       ");
		sql.append(" and B.V_MEAS_UNIT = C.PARAM_VALUE(+)");
		
		params.put("productCode", productCode);
		params.put("whCode", whCode);
		return this.jdbcDao.queryForList(sql.toString(), params, productRw);
	}
	/**
	 * 选择商品包装类
	 */
	private final AssRw productRw = new AssRw();	
	private static final class AssRw implements RowMapper{
		public Object mapRow(ResultSet rs, int rownum) throws SQLException {
			AssVo vo = new AssVo();
			vo.setProductCode(rs.getString("V_PRODUCT_CODE"));
			vo.setProductName(rs.getString("V_PRODUCT_NAME"));
			vo.setMeasUnit(rs.getString("V_MEAS_UNIT"));
			vo.setQty(rs.getLong("N_QTY"));
			vo.setStock(rs.getLong("leave_qty"));
			return vo;
		}
	}
	public Long findAssAmount(String productCode, String whCode) {
		StringBuffer sql = new StringBuffer();
		sql.append("select sum(wb.N_QTY) leave_qty               ");
		sql.append("  from EMP_T_WH_BALANCE wb                      ");
		sql.append(" where wb.V_WH_CODE = :whCode                    ");
		sql.append("   and wb.V_PRODUCT_CODE = :productCode ");
		Map params = new HashMap();
		params.put("productCode", productCode);
		params.put("whCode", whCode);
		List tmpList = this.jdbcDao.queryForList(sql.toString(), params,
				new RowMapper() {
					public Object mapRow(ResultSet rs, int idx) throws SQLException {
						return rs.getLong("LEAVE_QTY");
					}
				});
		if (tmpList.size() == 0) {
			return Long.valueOf(0);
		} else {
			return (Long) tmpList.get(0);
		}
	}
	public List<EmpTWhAssD> findAssd(String assCode){
		return super.baseDao.find(" FROM EmpTWhAssD WHERE assCode=?",assCode);
	}
}